package com.gujiangbo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.json.JSONObject;
import com.gujiangbo.cache.CacheService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/1/13 17:07
 * @Version: 1.0
 * @Description:
 */
@RestController
@RequestMapping("/api")
@Api("验证码")
@Slf4j
public class CheckCodeController {

    @Resource
    private CacheService cacheService;

    /**
     * 生成图片验证码
     *
     * @param request
     * @param response
     */
    @RequestMapping("/getImage")
    public void imgCode(HttpServletRequest request, HttpServletResponse response) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        try {
            request.getSession().setAttribute("CAPTCHA_KEY", lineCaptcha.getCode());
            String userID = request.getHeader("userID");
            response.setContentType("image/png");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            lineCaptcha.write(response.getOutputStream());
            cacheService.save(userID, lineCaptcha.getCode(), 60);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对验证码进行输入验证
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getverify", method = RequestMethod.POST)
    public JSONObject verify(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String verifyCode = request.getHeader("verifyCode");
        String userID = request.getHeader("userID");
        log.info("输入的验证码:" + verifyCode);
        if (StringUtils.isBlank(verifyCode)) {
            json.put("验证码验证结果", "验证码输入为空");
            return json;
        }
        String vCodeCache = cacheService.get(userID);
        if (StringUtils.isBlank(vCodeCache)) {
            json.put("验证码验证结果", "验证码已过期,请重新获取");
            return json;
        }
        if (vCodeCache.equals(verifyCode)) {
            json.put("验证码验证结果", "验证码正确");
        } else {
            json.put("验证码验证结果", "验证码失败");
        }
        return json;
    }
}
